package com.jcli._socket基恩士客户端;

import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.net.Socket;

public class TCPClient extends JFrame {
    private JTextField ipField;
    private JTextField portField;
    private JTextField messageField;
    private JButton sendButton;
    private JTextArea receivedDataArea;

    public TCPClient() {
        setTitle("TCP客户端");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(400, 300);
        setLocationRelativeTo(null);

        JPanel topPanel = new JPanel();
        topPanel.setLayout(new FlowLayout());

        JLabel ipLabel = new JLabel("服务器IP:");
        ipField = new JTextField(15);
        ipField.setText("127.0.0.1"); // 默认为本地回环地址

        JLabel portLabel = new JLabel("端口:");
        portField = new JTextField(5);
        portField.setText("9300"); // 默认端口号

        JLabel messageLabel = new JLabel("消息:");
        messageField = new JTextField(20);

        sendButton = new JButton("发送");
        receivedDataArea = new JTextArea(10, 30);
        receivedDataArea.setEditable(false);

        JScrollPane scrollPane = new JScrollPane(receivedDataArea);

        topPanel.add(ipLabel);
        topPanel.add(ipField);
        topPanel.add(portLabel);
        topPanel.add(portField);
        topPanel.add(messageLabel);
        topPanel.add(messageField);
        topPanel.add(sendButton);

        add(topPanel, BorderLayout.NORTH);
        add(scrollPane, BorderLayout.CENTER);

        sendButton.addActionListener(e -> {
            String ipAddress = ipField.getText();
            int port = Integer.parseInt(portField.getText());
            String message = messageField.getText();

            try {
                Socket socket = new Socket(ipAddress, port);

                OutputStream outputStream = socket.getOutputStream();
                PrintWriter writer = new PrintWriter(outputStream, true);
                writer.println(message); // 向服务器发送消息

                BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                String receivedData = reader.readLine(); // 从服务器接收消息
                receivedDataArea.append("接收到的消息: " + receivedData + "\n");

                writer.close();
                reader.close();
                socket.close();
            } catch (IOException exception) {
                exception.printStackTrace();
            }
        });
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            TCPClient client = new TCPClient();
            client.setVisible(true);
        });
    }
}
